﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TorchView.GameContent.Data;
using System.IO;

namespace TorchView.GameContent.Affixes
{
    public class AffixItemList
    {
        private List<Affix> _List;
        private SortedDictionary<string, Affix> _dictionary;
        private AffixItemList()
        {
            _List = new List<Affix>();
            _dictionary = new SortedDictionary<string, Affix>();

            IEnumerable<string> files = PakReader.GetFiles("media/Affixes/Items/", ".dat.adm", System.IO.SearchOption.AllDirectories);
            foreach(string filename in files)
            {
                Stream stream = PakReader.OpenFile(filename);
                if (stream != null)
                {
                    DataBlock block = AdmSerializer.Load(stream);
                    Affix affix = new Affix();
                    affix.LoadFromDataBlock(block);
                    _List.Add(affix);
                    if (!_dictionary.ContainsKey(affix.Name))
                    {
                        _dictionary.Add(affix.Name, affix);
                    }
                }
            }
        }

        public List<Affix> List { get { return _List; } }
        public List<Affix> GetListByType(string type)
        {
            List<Affix> list = new List<Affix>();
            foreach (Affix affix in _List)
            {
                if(affix.UnitTypes.HasUnitType(type))
                    list.Add(affix);
            }
            return list;
        }
        public ISet<string> GetUnitTypes()
        {
            SortedSet<string> types = new SortedSet<string>();
            foreach (Affix affix in _List)
            {
                foreach(string type in affix.UnitTypes.UnitTypes)
                {
                    if (type.Equals("WEAPON")) Console.WriteLine(affix);
                    types.Add(type);
                }
            }
            return types;
        }

        public Affix this[string name]
        {
            get 
            {
                Affix affix;
                if (_dictionary.TryGetValue(name, out affix))
                    return affix;
                else
                    return null;
            }

        }

        #region Static
        private static AffixItemList _itemList;
        public static AffixItemList DefaultList
        {
            get
            {
                if (_itemList == null)
                    _itemList = new AffixItemList();
                return _itemList;
            }
        }
        #endregion
    }
}
